/**
 * 描述: 业务逻辑处理 - 任务相关接口
 * 作者: kq
 * 日期: 2022-11-15
 */

const { querySql, handlePayload, insertOne } = require("../utils/index");
const jwt = require("jsonwebtoken");
const boom = require("boom");
const { validationResult } = require("express-validator");
const { CODE_ERROR, CODE_SUCCESS } = require("../utils/constant");
const { decode } = require("../utils/user-jwt");

// 出入库记录
function stockRecord(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    // 用户登录信息
    const yh = decode(req).username;
    const params = { ...handlePayload(req.body), yh };
    const query = "insert into t_crktz set ?";
    insertOne(query, params).then((data) => {
      if (!data || data.length === 0) {
        res.json({
          code: CODE_ERROR,
          msg: "添加数据失败",
          data: null,
        });
      } else {
        res.json({
          code: CODE_SUCCESS,
          msg: "添加数据成功",
          data: null,
        });
      }
    });
  }
}
// 使用量
function usageAmount(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    const yh = decode(req).username;
    const params = { ...handlePayload(req.body), yh };
    const query = "insert into t_sytz set ?";
    insertOne(query, params).then((data) => {
      if (!data || data.length === 0) {
        res.json({
          code: CODE_ERROR,
          msg: "添加数据失败",
          data: null,
        });
      } else {
        res.json({
          code: CODE_SUCCESS,
          msg: "添加数据成功",
          data: null,
        });
      }
    });
  }
}
// 自评批量插入
function selfEvaluation(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    const yh = decode(req).username;
    let params = req.body.scoreList;
    params.forEach(element => {
      element.push(yh)
    });
    const query = "insert into t_zpb(qymc, tbrq, itemxh, itemzpf, yh) value ?";
    insertOne(query, [params]).then((data) => {
      if (!data || data.length === 0) {
        res.json({
          code: CODE_ERROR,
          msg: "添加数据失败",
          data: null,
        });
      } else {
        res.json({
          code: CODE_SUCCESS,
          msg: "添加数据成功",
          data: null,
        });
      }
    });
  }
}

module.exports = {
  stockRecord,
  usageAmount,
  selfEvaluation
};
